package com.finals.finalsscreen.phone;

import java.io.File;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.finals.finalsscreen.app.BaseApplication;
import com.finals.finalsscreen.util.MusicPlayer;
import com.finals.finalsscreen.util.Util;

public class MyPhoneStateListener extends PhoneStateListener {

	BaseApplication mApplication;

	PhoneStateListen phoneStateListen;

	MusicPlayer musicPlayer;

	public MyPhoneStateListener(BaseApplication mApplication, PhoneStateListen phoneStateListen) {
		this.mApplication = mApplication;
		this.phoneStateListen = phoneStateListen;
		musicPlayer = new MusicPlayer(mApplication);
	}

	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
		super.onCallStateChanged(state, incomingNumber);
		switch (state) {
		case TelephonyManager.CALL_STATE_RINGING:
			Util.MuteRing(mApplication);
			phoneStateListen.setState(PhoneStateListen.CALL_STATE_RINGING);
			PlayMusic();
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
			Util.ReleaseMuteRing(mApplication);
			phoneStateListen.setState(PhoneStateListen.CALL_STATE_OFFHOOK);
			StopMusic();
			break;
		case TelephonyManager.CALL_STATE_IDLE:
			Util.ReleaseMuteRing(mApplication);
			phoneStateListen.setState(PhoneStateListen.CALL_STATE_IDLE);
			StopMusic();
			break;
		default:
			break;
		}
	}

	private void PlayMusic() {
		File mFile = getMediaFile();
		if (mFile != null && mFile.exists()) {
			musicPlayer.PlayMusic(mFile);
		}
	}

	private void StopMusic() {
		musicPlayer.Stop();
	}

	private File getMediaFile() {
		File mFile = null;
		ContentResolver contentResolver = mApplication.getContentResolver();
		String[] projection = new String[] { MediaStore.Audio.Media.DATA };
		Cursor cursor = null;
		try {
			cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (cursor != null) {
			cursor.moveToFirst();
		}
		if (cursor != null && cursor.moveToNext()) {
			String pathString = cursor.getString(0);
			mFile = new File(pathString);
		}
		try {
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mFile;
	}

}
